#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"

//GPIO9 控制 LED
#define LED_TASK_GPIO 8
//GPIO5 控制按键
#define IOT_GPIO_KEY 5
#define LED_INTERVAL_TIME 30
#define LED_TASK_STACK_SIZE 2048
#define LED_TASK_PRIO 25
enum LedState {
    LED_ON = 0,
    LED_OFF,
    LED_SPARK,
};
enum LedState g_ledState = LED_SPARK;
static void *LedTask(const char *arg)
{
    (void)arg;
    while (1) {
        /*根据按键切换 LED 的显示状态*/
        printf("g_ledState = %d\n",g_ledState);
        switch (g_ledState) {
            case LED_ON:
                IoTGpioSetOutputVal(LED_TASK_GPIO,0);
                osDelay(LED_INTERVAL_TIME);
                break;
            case LED_OFF:
                IoTGpioSetOutputVal(LED_TASK_GPIO,1);
                osDelay(LED_INTERVAL_TIME);
                break;
            case LED_SPARK:
                IoTGpioSetOutputVal(LED_TASK_GPIO,0);
                osDelay(LED_INTERVAL_TIME);
                IoTGpioSetOutputVal(LED_TASK_GPIO,1);
                osDelay(LED_INTERVAL_TIME);
                break;
            default:
                osDelay(LED_INTERVAL_TIME);
                break;
              }
    }
    return NULL;
}

unsigned int lastTickCount;
static void OnButtonPressed(char *arg)
{
 (void) arg;
 //消除按键抖动
    unsigned int tickCount = osKernelGetTickCount();
    unsigned int count = tickCount - lastTickCount;
    lastTickCount = tickCount;

    if (count < 50)
    {
        printf("----return\n");
        return ;


    }

    usleep(20*1000);

    /*按下按键的状态切换*/
    enum LedState nextState = LED_SPARK;

    switch (g_ledState) {
        case LED_ON:
            nextState = LED_SPARK;
            break;
        case LED_OFF:
            nextState = LED_ON;
            break;
        case LED_SPARK:
            nextState = LED_OFF;
            break;
        default:
            break;
    }
    g_ledState = nextState;
    printf("nextState=%d\n",nextState);
}

static void LedExampleEntry(void)
{
 osThreadAttr_t attr;
 /*LED 的 GPIO 初始化*/
 IoTGpioInit(LED_TASK_GPIO);
 /*GPIO 设置为输出*/
 IoTGpioSetDir(LED_TASK_GPIO,IOT_GPIO_DIR_OUT);
 
 /*按键 GPIO 初始化*/
 IoTGpioInit(IOT_GPIO_KEY);
 IoTGpioSetFunc(IOT_GPIO_KEY, 0);
 /*按键 GPIO 初始化为输入*/
 IoTGpioSetDir(IOT_GPIO_KEY, IOT_GPIO_DIR_IN);
 IoTGpioSetPull(IOT_GPIO_KEY, 1);
/*注册按键执行函数*/
 IoTGpioRegisterIsrFunc(IOT_GPIO_KEY, IOT_INT_TYPE_EDGE, 
                        IOT_GPIO_EDGE_FALL_LEVEL_LOW,
                        OnButtonPressed,
                        NULL);
 attr.name = "LedTask";
 attr.attr_bits = 0U;
 attr.cb_mem = NULL;
 attr.cb_size = 0U;
 attr.stack_mem = NULL;
 attr.stack_size = LED_TASK_STACK_SIZE;
 attr.priority = LED_TASK_PRIO;
 if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL) {
    printf("[LedExample] Falied to create LedTask!\n");
 }
}
SYS_RUN(LedExampleEntry);